<template>
  <div class="app-container " style="min-height:auto;overflow:auto" v-loading="pageLoading" :fullscreen="true"
    :element-loading-text="loadingText">
    <div class="p-20">
      <el-form ref="form" :model="data" label-width="auto">
        <el-row>
          <el-col :span="6">
            <el-form-item label="物料">
              <el-select filterable remote :remote-method="getMatOptions" clearable style="width:100%" size="medium"
                v-model="data.key_part_id" placeholder="请选择物料">
                <el-option v-for="o in skuOptions" :key="o.value" :label="o.label" :value="o.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-select filterable remote :remote-method="getVendorOptions" clearable style="width:100%" size="medium"
                v-model="data.vendor_id" placeholder="请选择供应商">
                <el-option v-for="o in vendorOptions" :key="o.value" :label="o.label" :value="o.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期">
              <el-date-picker value-format="yyyyMMdd" size="medium" v-model="data.date_code" style="width:100%"
                type="date" placeholder="选择生产日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产批次">
              <el-input v-model="data.lot" size="medium" placeholder="请输入生产批次"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单批数量(PCS)">
              <el-input-number v-model="data.lot_qty" :step="1" :step-strictly="true" :precision="0" :min="1"
                style="width:100%" label="请输入打印数量"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="打印数量">
              <el-input-number v-model="data.print_qty" style="width:100%" :step="1" :step-strictly="true" :min="1"
                :precision="0" label="请输入打印数量"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="50px">
              <el-button type="primary" @click="submit">标签打印</el-button>
              <el-button type="warning" @click="openModal" style="margin-left:30px">标签补印</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-card class="box-card" style="margin-top:10px">
          <div slot="header" style="color:#fff;font-weight:600" class="clearfix">
            打印记录
          </div>
          <div class="filter-container">
            <el-select filterable class="filter-item" v-model="query.type" placeholder="请选择标签类型">
              <el-option :key="0" label="全部" value=""></el-option>
              <el-option :key="1" label="正常打印" :value="1"></el-option>
              <el-option :key="2" label="标签补印" :value="2"></el-option>
            </el-select>
            <el-date-picker v-model="query.dateTime" size="medium" value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss" style="width:30%" class="filter-item" type="datetimerange"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
            </el-date-picker>
            <el-input v-model="query.sn" class="filter-item" style="width:20%" placeholder="请输入条码序号查询"></el-input>
            <el-button class="filter-item" plain @click="research">查询</el-button>
            <el-button class="filter-item" plain @click="reset">重置</el-button>
            <!-- <el-button class="filter-item fr" type="success" plain @click="research">导出</el-button> -->
          </div>
          <el-table v-loading="tableLoading" :data="list" @selection-change="select" style="width: 100%" :border="true">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column v-for="(v,index) in columns" :label="v.title" :prop="v.key" :width="v.width" :key="index">
            </el-table-column>
          </el-table>
          <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
            @change="getList"></z-pagination>
        </el-card>
        <el-dialog :title="'补印--请输入账号密码'" width="40%" :close-on-click-modal="false" :visible.sync="editFormVisible">
          <div>
            <el-form ref="form" :model="reprintingData" label-width="50px">
              <el-form-item label="账号">
                <el-input type="text" ref="inputName" v-model="reprintingData.user_id" @keyup.enter.native="nextInput">
                </el-input>
              </el-form-item>
              <el-form-item label="密码" class="mt-10">
                <el-input type="password" ref="password" v-model="reprintingData.password"
                  @keyup.enter.native="reprinting"></el-input>
              </el-form-item>
            </el-form>
            <div class="text-right" style="margin-top:30px">
              <el-button @click="editFormVisible = false">取消</el-button>
              <el-button type="primary" :loading="reprintLoading" @click="reprinting()">补印</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import mixinClient from '@/views/_common/mixinClient'
import zPagination from '@/views/_common/pagination'
import _ from 'lodash'
import { fileUrl } from '@/utils/index.js'
export default {
  name: 'materialPrint',
  mixins: [mixinClient],
  components: { zPagination },
  data() {
    return {
      reprintLoading: false,
      tableLoading: false,
      tabelHeight: 'auto',
      loadingText: '',
      columns: [
        { title: '标签类型', key: 'type_name', width: 120 },
        { title: '条码编号', key: 'serial_number', width: 250 },
        { title: '物料编号', key: 'key_part_no', width: 180 },
        { title: '物料名', key: 'key_part_name', width: 180 },
        { title: '供应商编号', key: 'vendor_code', width: 150 },
        { title: '供应商名称', key: 'vendor_name', width: 150 },
        { title: '生产日期', key: 'date_code', width: 130 },
        { title: '生产批次', key: 'lot', width: 130 },
        { title: '批次数量', key: 'lot_qty', width: 110 },
        { title: '打印模板名', key: 'temp_name', width: 150 },
        { title: '打印人', key: 'modify_user', width: 100 },
        { title: '打印时间', key: 'modify_time', width: 140 },
      ],
      skuOptions: [],
      vendorOptions: [],
      data: { lot_qty: 1, print_qty: 1 },
      list: [],
      total: 0,
      pageLoading: false,
      query: {
        size: 10,
        page: 1,
        start: '',
        end: '',
        sn: '',
      },
      editFormVisible: false,
      reprintingData: { user_id: '', password: '', valueList: [] },
      pagination: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, jumper, ->, total, sizes',
      },
    }
  },
  watch: {
    'data.key_part_id': {
      handler: function (newData, oldData) {
        this.query.keyPartId = newData
      },
    },
    'data.vendor_id': {
      handler: function (newData, oldData) {
        this.query.vendorId = newData
      },
    },
  },
  created() {},
  methods: {
    research() {
      this.getList()
    },
    reset() {
      this.query = { size: 10, page: 1 }
      this.getList()
    },
    nextInput() {
      this.$refs.password.focus()
    },
    openModal() {
      this.reprintingData.user_id = ''
      this.reprintingData.password = ''
      if (this.reprintingData.valueList.length <= 0) {
        this.$message.error('请勾选需要补印的数据。')
        return
      }
      this.editFormVisible = true
      this.$nextTick(() => {
        this.$refs.inputName.focus()
      })
    },
    select(v) {
      this.reprintingData.valueList = []
      if (!v || v.length <= 0) return
      this.reprintingData.key_part_id = v[0].key_part_id
      v.forEach((v) => {
        this.reprintingData.valueList.push(v.id)
      })
    },

    getMatOptions(query) {
      this.skuOptions = []
      if (query) {
        this.$request(this.$api.mat + 'getmatandsku', { queryString: query }).then((r) => {
          this.skuOptions = this.arrayOptions(r, 'id', ['key_part_no', 'key_part_name'])
        })
      }
    },
    getVendorOptions(query) {
      this.skuOptions = []
      if (query) {
        this.$request(this.$api.vendor + 'getlist', { queryString: query, size: 100, page: 1 }).then((r) => {
          this.vendorOptions = this.arrayOptions(r.list, 'id', ['vendor_code', 'vendor_name'])
        })
      }
    },

    arrayOptions(arr, v, l, text) {
      let r = []
      // 有text 并且text为数组
      if (text && !Array.isArray(text)) {
        console.error('text参数必须为数组且顺序和label参数一致')
        return false
      }
      if (!text) {
        text = []
      }
      arr.forEach((item) => {
        let data = ''
        if (!l) {
          data = item[v]
        } else if (Array.isArray(l)) {
          l.forEach((vtmp, index) => {
            data = data + ' ' + (text[index] ? text[index] : '') + item[vtmp]
          })
        } else {
          data = item[l]
        }
        if (item[v]) r.push({ value: item[v], label: data })
      })
      return r
    },

    getList() {
      this.tableLoading = true
      this.query.start = ''
      this.query.end = ''
      if (this.query.dateTime && this.query.dateTime.length > 0) {
        this.query.start = this.query.dateTime[0]
        this.query.end = this.query.dateTime[1]
      }
      this.$request(this.$api.materialprint + 'getlist', this.query)
        .then((r) => {
          this.list = r.list
          this.list.forEach((v) => {
            v.type_name = v.type == 1 ? '正常打印' : '标签补印'
          })
          this.total = r.total
        })
        .finally(() => {
          this.tableLoading = false
        })
    },

    submit() {
      this.loadingText = '正在打印中'
      this.pageLoading = true
      this.data.size = this.query.size
      this.data.page = this.query.page
      this.$request(this.$api.materialprint + 'generateprintdata', this.data, 'post')
        .then((r) => {
          this.getList()
          if (window.electron) {
            window.electron
              .print([
                {
                  fileUrl: fileUrl(this.$api.baseUrl, r.labelData.temp_url),
                  fileName: '',
                  label_qty: r.labelData.label_qty,
                  content: r.labelData.data_content,
                  directory: this.functionName,
                  soft_type: r.labelData.soft_type,
                },
              ])
              .then((r) => {
                this.clear()
                this.$message.success('打印成功')
                this.pageLoading = false
              })
              .catch((e) => {
                this.$message.error(e.toString())
                this.pageLoading = false
              })
          } else {
            this.pageLoading = false
          }
        })
        .catch((e) => {
          console.log(e.toString())
          this.pageLoading = false
        })
    },
    reprinting() {
      let data = { ...this.reprintingData }
      if (!data.user_id || !data.password) {
        this.$message.error('账号、密码不能为空。')
        return
      }
      this.reprintLoading = true
      this.$request(this.$api.materialprint + 'reprinting', data, 'post')
        .then((r) => {
          if (!r || r.length <= 0) {
            this.$message.error('未获取到打印数据。')
            this.pageLoading = false
            return
          }
          this.editFormVisible = false
          this.reprintLoading = false
          if (window.electron) {
            this.loadingText = '正在补印中'
            this.pageLoading = true
            let tmp = []
            r.forEach((v) => {
              tmp.push({
                fileUrl: fileUrl(this.$api.baseUrl, v.temp_url),
                fileName: '',
                label_qty: 1,
                content: v.data_content,
                directory: this.functionName,
                soft_type: v.soft_type,
              })
            })
            window.electron
              .print(tmp)
              .then((r) => {
                this.getList()
                this.reprintingData.valueList = []
                this.$message.success('补印成功')
                this.pageLoading = false
              })
              .catch((e) => {
                this.$message.error(e.toString())
                this.pageLoading = false
              })
          } else {
            this.reprintingData.valueList = []
            this.getList()
          }
        })
        .catch((e) => {
          this.reprintLoading = false
        })
    },
    clear() {
      this.data.date_code = ''
      this.data.lot = ''
      this.data.lot_qty = 1
      this.data.print_qty = 1
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/client.scss';
.z-panel-body .col-left {
  text-align: right;
  margin-bottom: 25px;
}
::v-deep .el-col {
  margin-bottom: 10px;
}
::v-deep .el-card {
  background: none;
  //   border: 1px solid #409eff;
}
::v-deep .el-card__header {
  //   background: #409eff;
  background: #333333;
}
::v-deep .el-card__header {
  padding: 10px 20px;
}
::v-deep .el-date-editor {
  height: 42px !important;
  background: #333;
}
::v-deep .el-range-input {
  border-top: 1px solid;
  border-bottom: 1px solid;
  font-size: 20px;
}
::v-deep .el-range-separator {
  color: #fff;
  line-height: 42px;
  height: 42px;
}
::v-deep .el-pagination {
  height: 42px;
}
::v-deep .el-pagination button {
  background: #333;
  height: 42px;
  line-height: 42px;
}
::v-deep .el-pagination button .number {
  background: #333;
}
::v-deep .el-pagination__rightwrapper {
  height: 42px;
  line-height: 42px;
}
::v-deep .el-pagination__total {
  background: #333;
  height: 42px !important;
  line-height: 42px !important;
  font-size: 20px !important;
  color: #fff;
}
::v-deep .el-pagination__jump {
  background: #333;
  height: 42px !important;
  line-height: 42px !important;
  font-size: 20px !important;
  color: #fff;
}
::v-deep .el-pager li {
  background: #333;
  color: #fff;
  height: 42px;
  line-height: 42px;
  font-size: 20px;
}

.z-panel-body .col-right {
  text-align: left;
  padding-left: 20px;
}
::v-deep .el-button:hover,
.el-button:focus {
  background: #333;
  border-color: #dcdfe6;
  color: #409eff;
}
::v-deep .el-input__inner {
  font-size: 20px !important;
}
::v-deep .el-dialog__body {
  background: #333;
  color: #fff;
}
::v-deep .el-dialog__header {
  background: #333;
  color: #fff;
}
</style>
